package com.kwlt.smc.http;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kwlt.smc.entity.HttpSmsEntity;
import com.kwlt.smc.util.ConUtils;
import com.kwlt.smc.util.Constants;
import com.kwlt.smc.util.SendHttpUtils;


public class Zb100Impl implements HttpSmsInter {
	
	public static Logger rptLog =  LoggerFactory.getLogger("zb100rpt");
	
	public static Logger mtLog =  LoggerFactory.getLogger("zb100mt");
	
	public static Logger moLog =  LoggerFactory.getLogger("zb100mo");
	/**
	 * 获取状态报告
	 */
	public void getHttpSmsRpt(HttpSmsEntity httpSmsEntity) {
		System.out.println(httpSmsEntity.getNumbers()+" rpt thread is run success!");
		Map<String, String> rptMap = getRptMap(httpSmsEntity);
		while(true){
			String rpt = SendHttpUtils.sendHttpPostRequest(httpSmsEntity.getRptUrl(), rptMap,"GB2312");
			if(rpt!=null && !"".equals(rpt)){
				if(!rpt.equals("-1")&&!rpt.equals("-2")&&!rpt.equals("-3")&&!rpt.equals("-17")
						&&!rpt.equals("-20")&&!rpt.equals("-21")&&!rpt.equals("-99")&&!rpt.equals("-100")){
					for(String singleRpt: rpt.split((char)3+"")){
						String[] split = singleRpt.split((char)2+"");
						if(split!=null && split.length==3){
							String messageId = split[0];
							String phone = split[1];
							String rptValue = split[2];
							String rptVa = "";
							if("DELIVRD".equals(rptValue)){
								rptVa = "0";
							}else{
								rptVa = "1";
							}
							//查找临时文件
							File file = FileUtils.getFile(httpSmsEntity.getTmpPath()+messageId+phone);
							if(file!=null){
								String localMsgId = getLocalMsgId(file);
								if(Constants.UNICOM.equals(httpSmsEntity.getOperators())){
									createUnicomRptFile(httpSmsEntity, phone, rptVa, localMsgId, messageId,file);
								}else if(Constants.TELECOM.equals(httpSmsEntity.getOperators())){
									createTelecomRptFile(httpSmsEntity, phone, rptValue, localMsgId, messageId,file);
								}
							}else{
								rptLog.info("not find tmp file:"+singleRpt);
							}
						}
					}
				}else{
					rptLog.info("查询状态报告异常||异常代码"+rpt);
				}
			}
			ConUtils.threadSleep(10000);
		}
	}

	/**
	 * 组装http发送map
	 * @param phone 手机号
	 * @param msg 发送内容
	 * @param httpSmsEntity 用户名和密码实体类
	 * @param expaCode 扩展码
	 * @return
	 */
	public Map<String,String> getSendMap(String phone,String msg,HttpSmsEntity httpSmsEntity,String expaCode){
		Map<String,String> map = new HashMap<String,String>();
		map.put("username", httpSmsEntity.getUserName());
		map.put("password", httpSmsEntity.getPassword());
		map.put("mobile", phone);
		map.put("message", msg);
		if(expaCode!=null && !"".equals(expaCode)){
			map.put("Ext", expaCode);
		}
		return map;
	}
	/**
	 * 发送短信
	 */
	public void sendHttpSms(HttpSmsEntity httpSmsEntity) {
		System.out.println(httpSmsEntity.getNumbers()+ " mt thread is run success!");
		File mtFile = FileUtils.getFile(httpSmsEntity.getMtPath());
		while(true){
			for(File file:mtFile.listFiles()){
				try {
					List<String> list = FileUtils.readLines(file, "GBK");
					if(list!=null && list.size()>0){
						String phone = list.get(6);
						String accessNumber = list.get(11);
						String localMsgId = list.get(18);
						String msg = list.get(20);
						//截取扩展码
						String expaCode = accessNumber.substring(httpSmsEntity.getAccessNumbers().length(),accessNumber.length());
						Map<String, String> sendMap = getSendMap(phone, msg, httpSmsEntity, expaCode);
						String request = SendHttpUtils.sendHttpPostRequest(httpSmsEntity.getSendUrl(), sendMap,"GB2312");
						mtLog.info("send http sms:"+phone+"\t"+accessNumber+"\t"+localMsgId+"\t"+msg+"\t"+request);
						FileUtils.writeStringToFile(new File(httpSmsEntity.getTmpPath()+request+phone),localMsgId,"GBK");
						file.delete();
						//如果返回大于0则代表提交成功
						/*if(Integer.parseInt(request)>0){
							//则将成功返回的消息ID和手机号作为文件名生成临时文件到临时目录,并且删除MT文件
							FileUtils.writeStringToFile(new File(httpSmsEntity.getTmpPath()+request+phone),localMsgId,"GBK");
							file.delete();
						}else{
							//否则继续提交
							mtLog.info("短信发送异常||异常代码"+request);
							break;
						}*/
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ConUtils.threadSleep(1000);
		}
	}
	
	public String getLocalMsgId(File tmpFile){
		try {
			List<String> list = FileUtils.readLines(tmpFile, "GBK");
			if(list!=null && list.size()>0)
				return list.get(0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 生成电信状态报告文件
	 * @param httpSmsEntity
	 * @param phone 手机号
	 * @param rptValue 状态报告成功值
	 * @param localMsgId 
	 * @return
	 */
	public void createTelecomRptFile(HttpSmsEntity httpSmsEntity,String phone,String rptValue,
			String localMsgId,String messageId,File tmpFile){
		StringBuffer rptFileCont = new StringBuffer();
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append(phone).append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append(localMsgId).append("\n");
		rptFileCont.append("\n");//
		rptFileCont.append("RPT ").append(rptValue).append("\n");
		rptFileCont.append(messageId).append("\n");
		try {
			FileUtils.writeStringToFile(new File(httpSmsEntity.getRptPath()+messageId+phone+ConUtils.formatseq()), 
					rptFileCont.toString(),"GBK");
			tmpFile.delete();
			rptLog.info("telecom rpt file message:"+phone+"\t"+localMsgId+"\t"+messageId+"\t"+rptValue);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 生成联通状态报告
	 * @param httpSmsEntity
	 * @param phone
	 * @param rptValue
	 * @param localMsgId
	 * @param messageId
	 */
	public void createUnicomRptFile(HttpSmsEntity httpSmsEntity,String phone,String rptValue,
			String localMsgId,String messageId,File tmpFile){
		StringBuffer rptFileCont = new StringBuffer();
		rptFileCont.append(messageId).append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append(phone).append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append(localMsgId).append("\n");
		rptFileCont.append("\n");//
		rptFileCont.append("RPT ").append(rptValue).append("\n");
		rptFileCont.append("\n");
		try {
			FileUtils.writeStringToFile(new File(httpSmsEntity.getRptPath()+messageId+phone+ConUtils.formatseq()), 
					rptFileCont.toString(),"GBK");
			tmpFile.delete();
			rptLog.info("unicom rpt file message:"+phone+"\t"+localMsgId+"\t"+messageId+"\t"+rptValue);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 组装http获取状态报告map
	 * @param httpSmsEntity
	 * @return
	 */
	public Map<String,String> getRptMap(HttpSmsEntity httpSmsEntity){
		Map<String,String> map = new HashMap<String,String>();
		map.put("username", httpSmsEntity.getUserName());
		map.put("password", httpSmsEntity.getPassword());
		return map;
	}
	/**
	 * 获取mo
	 */
	public void getHttpSmsMo(HttpSmsEntity httpSmsEntity){
		System.out.println(httpSmsEntity.getNumbers()+ " mo thread is run success!");
		Map<String, String> rptMap = getRptMap(httpSmsEntity);
		while(true){
			String mo = SendHttpUtils.sendHttpPostRequest(httpSmsEntity.getMoUrl(), rptMap,"GB2312");
			if(mo!=null && !"".equals(mo)){
				if(!mo.equals("-1")&&!mo.equals("-2")&&!mo.equals("-3")&&!mo.equals("-17")
						&&!mo.equals("-20")&&!mo.equals("-99")&&!mo.equals("-100")){
					for(String singleMo: mo.split((char)3+"")){
						String[] split = singleMo.split((char)2+"");
						if(split!=null && split.length==5){
							String phone = split[0];//手机号
							String content = split[1];//回复内容
							String date = split[2];//回复时间
							String expaCode = split[3];//扩展码
							String messageId = split[4];//批次号
							createMoFile(httpSmsEntity, phone, content, date, expaCode, messageId);
						}
					}
				}else{
					moLog.info("查询上行异常||异常代码"+mo);
				}
			}
			ConUtils.threadSleep(6000);
		}
	}
	
	/**
	 * 创建Mo文件
	 * @param httpSmsEntity
	 * @param phone
	 * @param content
	 * @param date
	 * @param expaCode
	 * @param messageId
	 */
	public void createMoFile(HttpSmsEntity httpSmsEntity,String phone,String content
			,String date,String expaCode,String messageId){
		StringBuffer moFileCont = new StringBuffer();
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append(phone).append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append(httpSmsEntity.getAccessNumbers()+expaCode).append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append(content).append("\n");
		try {
			FileUtils.writeStringToFile(new File(httpSmsEntity.getRptPath()+messageId+phone+ConUtils.formatseq()), 
					moFileCont.toString(),"GBK");
			moLog.info("mo file message:"+phone+"\t"+date+"\t"+messageId+"\t"+expaCode+"\t"+content);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
